

from rest_framework import serializers
from users.models import User
from django.contrib.auth.models import Group
from django.contrib.auth.hashers import make_password


class AdminGroupModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = [
            'id',
            'name'
        ]



class AdminModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'email',
            'mobile',

            'password',
            'groups',
            'user_permissions'
        ]

        extra_kwargs = {
            'password': {'write_only': True}
        }


    def validate(self, attrs):
        # 1、密码加密；2、添加is_staff=True
        password = attrs.get('password')
        attrs['password'] = make_password(password)
        attrs['is_staff'] = True
        return attrs

    # def create(self, validated_data):
    #     groups = validated_data.pop('groups')
    #     user_permissions = validated_data.pop('user_permissions')
    #
    #     # 1、新建主表对象
    #     user =  User.objects.create_superuser(**validated_data)
    #     # 2、创建从表数据
    #     user.groups.set(groups)
    #     user.user_permissions.set(user_permissions)
    #
    #     return user



